from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'

# Order matters: Initialize SQLAlchemy before Marshmallow
db = SQLAlchemy(app)
ma = Marshmallow(app)


class Author(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(255))

class Book(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(255))
    author_id = db.Column(db.Integer, db.ForeignKey('author.id'))
    author = db.relationship('Author', backref='books')


class AuthorSchema(ma.ModelSchema):
    class Meta:
        model = Author

class BookSchema(ma.ModelSchema):
    class Meta:
        model = Book

if __name__ == '__main__':
    # db.create_all()
    author_schema = AuthorSchema()
    book_schema = BookSchema()
    author = Author(name='Chuck Paluhniuk')
    book = Book(title='Fight Club', author=author)
    db.session.add(author)
    db.session.add(book)
    db.session.commit()
    a = author_schema.dump(author).data
    print(a)

